package com.jida.weather.service;

import com.jida.weather.domain.WeatherResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

@Service
public class WeatherServiceImpl implements WeatherService {

    //SpringWeb提供了一个接口：RestTemplate  专门在程序中访问第三方接口
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RestTemplate restTemplate;


    @Override
    public WeatherResponse accessThree(String city){
        String url="https://apis.tianapi.com/tianqi/index?key="+"98abbbc0497bf93842385bc13a903f46"+"&city="+city+"&type=1";
        System.out.println("url:"+url);
        WeatherResponse weatherResponse=restTemplate.getForObject(url, WeatherResponse.class);

        return weatherResponse;
    }

    @Override
    public void cacheWeatherData(String city) {
        /**
         1.先查
         2.保存到redis数据库
         */
        System.out.println("我正在查询并缓存城市编号为："+city+"的天气数据"+new Date());
        WeatherResponse weatherResponse= accessThree(city);

        redisTemplate.opsForHash().put("jinandaxueweatherdata",city,weatherResponse);
                /*
                weatherdata:  guangzhou :---------------------
                              meizhou:----------------------
                              zhanjiang:---------------------
                              huizhou:------------------------
                 */
    }

}
